let viewer = document.getElementById('viewer')
let bookType = 'pdf'
let catelogFlag = true
//进度
let curSiteX = 0
let progress = 0
let draging = false
let limitLeft = $('.operate_low .progress')[0].offsetLeft
let limitRight = $('.operate_low .progress')[0].offsetWidth
//epub
let book = null
let rendition = null
let curStart = {index: 0}//为防止前一章直接翻到底单独处理
//status
let toc = []
let curSectionIndex = 0
let curFontSize = 0
let readerMode = 0
let fontSize = 'mini'
//查词
let iframeId  = ''
let keyword = ''
if(bookType === 'pdf'){
    readPdf()
}else if(bookType === 'epub'){
    readEpub()
}

function download(){
    let source = 'http://ebook2.zhiyuext.com/FileApi/File/Download?fileid=3281'
    // let source = 'http://ebook2.zhiyuext.com/FileApi/File/Download?fileid=3000'
    let xhr = new XMLHttpRequest()
    let flag = true
    xhr.responseType = 'blob'
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            if(xhr.status === 200){
                $('#res').text('成功')
                let file = new File(xhr.response, 'mybook.pdf', {type: 'application/pdf'})
                let url = URL.createObjectURL(xhr.response)
                window.open(url)
            }else{
                $('#res').text('失败')
            }
        }
    }
    xhr.onprogress = function(res){
        if(flag){
            let progress = Math.floor(res.loaded / res.total * 100)
            console.log(progress)
            $('#res').text(progress)                 
        }
    }
    xhr.open('GET', source)
    xhr.send()
}

//pdf阅读器
function readPdf(){
    let url  = 'shizhan.pdf'                
    let loadingTask = pdfjsLib.getDocument(url)
    
    $('#pre').html('上一页')
    $('#next').html('下一页')
    loadingTask.promise.then(function(pdf) {
        console.log(pdf)
        pdf.getOutline().then(outline=>{
            console.log('目录')
            console.log(outline)
            initCatelog(outline, pdf)
            if(!outline){
                //无目录
                catelogFlag = false
                return
            }
            
            // outline.forEach(e=>{
            //     let linkString = pdf.getDestination(e.dest)
            //     html += `<a href="${linkString}" class="cate" >${e.title}</a>`
            // })
        })
        $('#loading').hide()
        for(let i=1;i<=pdf._pdfInfo.numPages;i++){
            renderPage(pdf, i)
        }
        initSeeker()
        managePage()
        manageSetting()
    })
    function renderPage(pdf, index){
        pdf.getPage(index).then(function(page){
            if(index < 4 ){
                console.log(page)
                console.log(page.ref)
            }
            let scale = 1.5
            let viewport = page.getViewport({ scale: scale, })
            // Support HiDPI-screens.
            let outputScale = window.devicePixelRatio || 1

            let canvas = document.createElement('canvas')
            canvas.id = getDestinationHash(page.ref)
            canvas.style.cssText = 'margin: 0 auto;display: block;'
            viewer.appendChild(canvas)
            let context = canvas.getContext('2d')

            canvas.width = Math.floor(viewport.width * outputScale)
            canvas.height = Math.floor(viewport.height * outputScale)
            canvas.style.width = Math.floor(viewport.width) + "px"
            canvas.style.height =  Math.floor(viewport.height) + "px"

            let transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null

            let renderContext = {
                canvasContext: context,
                transform: transform,
                viewport: viewport
            }
            page.render(renderContext)
        })
    }
    function initCatelog(outline, pdf){
        let html = '<div style="height: 100vh;overflow:scroll;padding-top:40px;">'
        outline.forEach(e=>{
            let linkString = getDestinationHash(e.dest)
            html += `<div class="cate" data-url="${linkString}" onclick="turnSection(event)">${e.title}</div>`
        })
        html += '</div>'
        $('#catelog').html(html)
        $('#spine').click(e=>{
            if(!catelogFlag){
                return
            }
            $('#catelog').slideDown('fast')
        })
        //目录
        $('#catelog').click(e=>{
            $('#catelog').fadeOut()
        })
        $('#catelog .cate').click(e=>{
            $('#catelog').fadeOut()
        })
    }
    function getDestinationHash(dest) {
        if (typeof dest === "string") {
          if (dest.length > 0) {
            return getAnchorUrl(encodeURIComponent(dest))
          }
        } else if (Array.isArray(dest)) {
          const str = JSON.stringify(dest);
          if (str.length > 0) {
            return getAnchorUrl(encodeURIComponent(str))
          }
        }
        return getAnchorUrl("")
    }
    function getAnchorUrl(str){
        let baseUrl = ''
        return (baseUrl || "") + str
    }
    
    function initSeeker(){
        manageProgress()
        $('#viewer').on('scroll', throttle(scrollHandler, 300))
        function scrollHandler(e){
            console.log(e.currentTarget)
            let viewer = e.currentTarget
            let progress = Math.floor(viewer.scrollTop / viewer.scrollHeight * 100)
            updateProgress(progress)
        }
    }
}

//pdf 阅读器
function readEpub(){
    init()
    let fileId = encodeURI(getQuery(location.href).fileid)
    let source = 'http://ebook2.zhiyuext.com/FileApi/File/Download?fileid=233'
    // let source = 'http://ebook2.zhiyuext.com/FileApi/File/Download?fileid=1132'
    if(fileId !== 'undefined'){
        source = `http://ebook2.zhiyuext.com/FileApi/File/Download?fileid=${fileId}`
    }
    // let source = 'http://192.168.191.1:20000/aq.epub'
    // let source = 'aq.epub'
    
    
    book = ePub(source, {openAs: 'epub'})

    book.ready.then((res)=>{
        return book.locations.generate()
    })
    rendition = book.renderTo('viewer', {
        // manager: "continuous",
        // flow: "scrolled-doc",
        flow: "scrolled",
        width: "100%",
        height: "100%"
    })
    rendition.hooks.render.register(function (view) {
        // view.contents.addScript('http://192.168.191.1:20000/bookScript.js')
        view.contents.addScript('../js/bookScript.js')
    })

    rendition.on('relocated', function(location){
        curStart = location.start
        let percent = book.locations.percentageFromCfi(location.start.cfi);
        let percentage = Math.floor(percent * 100);
        if(!draging) {
            progress = percentage;
        }
        updateProgress(progress)
    })
    
    
    rendition.on('displayError', function(err){
        console.log(err)
    })
    //查词
    $('#baike').on('click', ()=>{
        $('#contextMenu').hide()
        let src = encodeURI(`https://baike.baidu.com/item/${keyword}`)    
        $('#thirdLink iframe').attr('src', src)
        $('#thirdLink').show()

    })
    $('#thirdLink iframe').on('click', (e)=>{e.stopPropagation()})
    $('#thirdLink').on('click', ()=>{
        $('#thirdLink').hide()
    })
    rendition.on('rendered', function(){
        try{
            if(rendition.views()['_views'][0]){
                iframeId = rendition.views()['_views'][0].id
            }
        }catch(err){
            console.log(err)
        }
    })
    rendition.on("selected", function(range,contents) {
        book.getRange(range).then(res=>{
            keyword = res.toString()
        })
        // let childWin = document.getElementById(iframeId).contentWindow
        // let rg = rendition.getRange(range)
    })
    rendition.themes.register("light", "../css/themes.css");
    rendition.themes.register("dark", "../css/themes.css");
    rendition.themes.select("light");

    book.loaded.navigation.then(res=>{
        $('#loading').hide()
        if(res.toc instanceof Array){
            let html = '<div style="height: 100vh;overflow:scroll;padding-top:40px;">'
            res.toc.forEach(e=>{
                html += `<div class="cate" data-url="${e.href}" onclick="turnSection(event)">${e.label}</div>`
            })
            html += '</div>'
            $('#catelog').html(html)
        }
    })
    rendition.display(1)
    managePage()
    function init(){
        let temp = localStorage.getItem('store')
        if(temp){
            // alert(temp)
        }else{
            localStorage.setItem('store', 'jin')
        }
        //设置
        manageSetting()
        $('#spine').click(e=>{
            $('#catelog').slideDown('fast')
        })
        //目录
        $('#catelog').click(e=>{
            $('#catelog').fadeOut()
        })
        $('#catelog .cate').click(e=>{
            $('#catelog').fadeOut()
        })
        //进度
        manageProgress()
    }
    function moveProgressBar(){
        let currentLocation = rendition.currentLocation()
        let currentPage = book.locations.percentageFromCfi(currentLocation.start.cfi)
        let progress = currentPage ? Math.ceil(currentPage * 100) : 0
        updateProgress(progress)
    }
    
    
    //选区菜单
    $('body').on('click', lockOut)
    $('#contextMenu').on('click', (e)=>{
        e.stopPropagation()
    })
    function lockOut(){
        $('#contextMenu').hide()
    }
    function lockOn(x, y){
        $('#contextMenu').css({left: `${x-30}px`, top: `${y-48}px`}).show()
    }

    function getQuery(str){
        if(!/\?/.test(str)){
            return false
        }
        str = decodeURI(str)
        let queryString = str.split('?')[1]
        let querys = queryString.split('&')
        let obj = {}
        querys.forEach(e => {
            let arr = e.split('=')
            obj[arr[0]] = arr[1]
        })
        return obj
    } 
    function collectBook(){
        let query = getQuery(location.href)
        const data = {
            readerId: query.readerid,
            readerUuid: query.readeruuid,
            userType: query.usertype,
            eBookId: query.ebookid,
            addOrRemove: 1,
            fromwhat: 3
        }
        fetch('http://ebook2.zhiyuext.com/EBookApi/ReaderEBookShelf/AddOrRemove', {
            method: 'POST',
            headers:{
                'Authorization': 'Bearer ' + query.token,
                'Content-Type': 'application/json' 
            },
            body: JSON.stringify(data)
        }).then(res=>{
            showToast('已添加到书架')
        }).catch(err=>{
            showToast('添加失败')
        })
    }
    function showToast(msg){
        let toast = document.createElement('div')
        toast.className = 'cus_toast'
        toast.style.cssText = `position: fixed;
                                width: 70%;
                                text-align: center;
                                padding: 12px 20px;
                                border-radius: 6px;
                                word-break: break-all;
                                background: rgba(0,0,0,0.6);
                                color: white;
                                top: 30%;
                                left: 50%;
                                transform: translate(-50%, -50%)`
        $(toast).html(msg)
        $('body').append(toast)
        setTimeout(()=>{
            $(toast).remove()
            toast = null
        }, 1500)                    
    }
}

//通用操作
function turnSection(event){
    if(bookType === 'epub'){
        rendition.display(event.target.dataset.url)
    }else{
        location.hash = event.target.dataset.url
    }
}
function throttle(fn,wait){
    let timer = null;
    return function(){
        let context = this;
        let args = arguments;
        if(!timer){
            timer = setTimeout(function(){
                fn.apply(context,args);
                timer = null;
            },wait)
        }
    }
}
function manageProgress(){
    $('.fastener').on('touchstart',function(e){
        draging = true
        curSiteX = e.touches[0].clientX
    })
    $('.fastener').on('touchmove',function(e){
        if(!draging){
            return
        }
        let dx = e.touches[0].clientX - limitLeft
        if(dx < 0){
            dx = 0
        }
        if(dx > limitRight){
            dx = limitRight
        }
        progress = Math.ceil(dx / limitRight * 100)
        updateProgress(progress, dx)
        
    })
    $('.fastener').on('touchend',function(e){
        if(!draging){
            return
        }
        if(bookType === 'epub'){
            let cfi = book.locations.cfiFromPercentage(progress / 100);
            rendition.display(cfi);    
        }else{
            let percentage =  progress / 100
            $('#viewer')[0].scrollTop = $('#viewer')[0].scrollHeight * percentage
        }  
        draging = false            
    })
    $('.fastener').on('touchleave',function(e){
        draging = false
    })
    $('.fastener').on('touchcancel',function(e){
        draging = false
    })
}

function updateProgress(progress, dx){
    //进度更新
    if(typeof dx !== 'number'){
        dx = Math.ceil(limitRight * progress / 100)
    }
    $('.fastener').css('transform', `translateX(${dx}px)`)
    $('.trunk').css('width', `${progress}%`)
    $('#percentage').html(progress)
}

function managePage(){
    $('#pre').on('click', (e)=>{
        if(bookType === 'epub'){
            if(!curStart.index){
                return
            }
            rendition.display(curStart.index - 1)
            // rendition.prev()
            e.preventDefault()
        }else{
            let scrollTarget = $('#viewer')[0].scrollTop - $('#viewer')[0].offsetHeight
            if(scrollTarget < 0){
                scrollTarget = 0
            }
            $('#viewer')[0].scrollTop = scrollTarget
        }
    })
    $('#next').on('click', (e)=>{
        if(bookType === 'epub'){
            rendition.next()
            e.preventDefault()
        }else{
            let scrollTarget = $('#viewer')[0].scrollTop + $('#viewer')[0].offsetHeight
            let scrollLimit = $('#viewer')[0].scrollHeight - $('#viewer')[0].offsetHeight
            if(scrollTarget > scrollLimit){
                scrollTarget = scrollLimit
            }
            $('#viewer')[0].scrollTop = scrollTarget
        }
    })
}
function manageSetting(){
    console.log('bookType')
    if(bookType === 'pdf'){
        $('#setting').css('color', '#d2d3d2')
        return
    }
    $('#setting').click(e=>{
        $('#setting_options').toggle()
    })
    $('.setting_row .font').click(function(){
        $(this).addClass('act').siblings().removeClass('act')
            if(bookType === 'epub'){
            curFontSize = $('.setting_row .font').index(this)
            if(curFontSize === 0){
                rendition.themes.fontSize("100%")
            }else if(curFontSize === 1){
                rendition.themes.fontSize("120%")
            }else{
                rendition.themes.fontSize("150%")
            }
        }
    })
    $('.setting_row .mode').click(function(){
        $(this).addClass('act').siblings().removeClass('act')
        if(bookType === 'epub'){
            readerMode = $('.setting_row .mode').index(this)
            if(readerMode === 0){
                rendition.themes.select('light')
            }else{
                rendition.themes.select('dark')
            }
        }
    })

    //添加、移出书架
    $('.cancelBtn').click(function(){
        $('.dialog').hide()
    })
    $('.confirmBtn').click(function(){
        $('.dialog').hide()
        //移出书架 待定
    })
    $('.removeBook').click(function(){
        $('.dialog').show()
    })
}